package catering

import (
	"errors"
	"gitee.com/g-qs/gin-vue-admin/server/global"
	"gitee.com/g-qs/gin-vue-admin/server/model/catering"
	cateringReq "gitee.com/g-qs/gin-vue-admin/server/model/catering/request"
	cateringRes "gitee.com/g-qs/gin-vue-admin/server/model/catering/response"
	"gitee.com/g-qs/gin-vue-admin/server/model/common/request"
	"gitee.com/g-qs/gin-vue-admin/server/model/disease"
	"gitee.com/g-qs/gin-vue-admin/server/model/hierarchy"
	"gitee.com/g-qs/gin-vue-admin/server/utils"
	"gorm.io/gorm"
	"strings"
	"time"
)

type FoodService struct {
}

// CreateFood 创建配餐记录
// Author [piexlmax](https://github.com/piexlmax)
func (foodService *FoodService) CreateFood(food *catering.Food) (err error) {
	err = global.GVA_DB.Create(food).Error
	return err
}

// DeleteFood 删除配餐记录
// Author [piexlmax](https://github.com/piexlmax)
func (foodService *FoodService) DeleteFood(food catering.Food) (err error) {
	err = global.GVA_DB.Delete(&food).Error
	return err
}

// DeleteFoodByIds 批量删除配餐记录
// Author [piexlmax](https://github.com/piexlmax)
func (foodService *FoodService) DeleteFoodByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]catering.Food{}, "id in ?", ids.Ids).Error
	return err
}

// UpdateFood 更新配餐记录
// Author [piexlmax](https://github.com/piexlmax)
func (foodService *FoodService) UpdateFood(food catering.Food, user_id uint) (err error) {
	updateMap := make(map[string]interface{})
	if food.Breakfast != nil {
		updateMap["breakfast"] = *food.Breakfast
	}
	if food.Lunch != nil {
		updateMap["lunch"] = *food.Lunch
	}
	if food.Dinner != nil {
		updateMap["dinner"] = *food.Dinner
	}
	today := time.Now().Format("2006-01-02")
	tomorrow := time.Now().AddDate(0, 0, 1).Format("2006-01-02")
	err = global.GVA_DB.Model(&catering.Food{}).Where("user_id = ? and date BETWEEN ? AND ?", user_id, today, tomorrow).Updates(updateMap).Error
	return err
}

// GetFood 根据id获取配餐记录
// Author [piexlmax](https://github.com/piexlmax)
func (foodService *FoodService) GetFood(user_id uint) (foodRes *catering.FoodRes, err error) {
	//获取今天零点和明天零点
	var food *catering.Food
	today := time.Now().Format("2006-01-02")
	tomorrow := time.Now().AddDate(0, 0, 1).Format("2006-01-02")
	ferr := global.GVA_DB.Where("user_id = ? and date BETWEEN ? AND ?", user_id, today, tomorrow).First(&food).Error
	var foodPlan disease.DiseaseReportPlan
	var teaPlan disease.DiseaseReportPlan
	var record disease.DiseaseReportRecord

	err = global.GVA_DB.Order("created_at Desc").Limit(1).First(&record, "uid = ?", user_id).Error
	if err != nil {
		return nil, errors.New("此用户未生成报告")
	}
	err = global.GVA_DB.First(&foodPlan, "drr_id = ? and types = ?", record.ID, 4).Error
	err = global.GVA_DB.First(&teaPlan, "drr_id = ? and types = ?", record.ID, 3).Error
	var foods []hierarchy.FdArticleGraphic
	var tea []hierarchy.FdArticleGraphic

	idsStr := strings.Trim(foodPlan.IDs, "[]")

	teaIdsStr := strings.Trim(teaPlan.IDs, "[]")

	// Split the string into an array
	idsArr := strings.Split(idsStr, ",")

	teaIdsArr := strings.Split(teaIdsStr, ",")

	foodErr := global.GVA_DB.Find(&foods, "id in (?)", idsArr).Error
	if foodErr != nil {
		return nil, errors.New("此用户无配餐")
	}
	teaErr := global.GVA_DB.Find(&tea, "id in (?)", teaIdsArr).Error
	if teaErr != nil {
		return nil, errors.New("此用户无体质茶")
	}
	if errors.Is(ferr, gorm.ErrRecordNotFound) {
		food = &catering.Food{
			UserID: user_id,
			Date:   utils.Pointer(time.Now()),
		}
		err = global.GVA_DB.Create(&food).Error
	}
	var res catering.FoodRes
	res.ID = food.ID
	res.UserID = food.UserID
	res.Date = food.Date
	if food.Breakfast == nil {
		res.Breakfast = foods
	} else {
		ierr := global.GVA_DB.Find(&res.Breakfast, "id in (?)", food.Breakfast).Error
		res.IsSelectBreakfast = true
		if ierr != nil {
			return nil, ierr
		}
	}
	if food.Lunch == nil {
		res.Lunch = foods
	} else {
		ierr := global.GVA_DB.Find(&res.Lunch, "id in (?)", food.Lunch).Error
		res.IsSelectLunch = true
		if ierr != nil {
			return nil, ierr
		}
	}
	if food.Dinner == nil {
		res.Dinner = foods
	} else {
		ierr := global.GVA_DB.Find(&res.Dinner, "id in (?)", food.Dinner).Error
		res.IsSelectDinner = true
		if ierr != nil {
			return nil, ierr
		}
	}
	res.Tea = tea

	return &res, nil
}

// GetFoodInfoList 分页获取配餐记录
// Author [piexlmax](https://github.com/piexlmax)
func (foodService *FoodService) GetFoodInfoList(info cateringReq.FoodSearch) (list []catering.Food, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&catering.Food{})
	var foods []catering.Food
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.Date != nil {
		db = db.Where("date = ?", info.Date)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&foods).Error
	return foods, total, err
}

// GetLastPlanList 获取最近方案记录
// Author [g-qs](https://github.com/g-qs)
func (foodService *FoodService) GetLastPlanList(userID string) (list cateringRes.Response, err error) {
	var plan catering.Food
	var audio hierarchy.FdArticleAudio
	var video hierarchy.FdArticleVideo
	var breakfast hierarchy.FdArticleGraphic
	var lunch hierarchy.FdArticleGraphic
	var dinner hierarchy.FdArticleGraphic
	err = global.GVA_DB.Order("created_at Desc").Limit(1).First(&plan, "user_id = ?", userID).Error
	if plan.Brain != nil {
		err = global.GVA_DB.Where("id = ?", plan.Brain).First(&audio).Error
	}
	if plan.Sport != nil {
		err = global.GVA_DB.Where("id = ?", plan.Sport).First(&video).Error
	}
	if plan.Breakfast != nil {
		err = global.GVA_DB.Where("id = ?", plan.Breakfast).First(&breakfast).Error
	}
	if plan.Lunch != nil {
		err = global.GVA_DB.Where("id = ?", plan.Lunch).First(&lunch).Error
	}
	if plan.Dinner != nil {
		err = global.GVA_DB.Where("id = ?", plan.Dinner).First(&dinner).Error
	}
	list = cateringRes.Response{
		ID:        plan.ID,
		CreatedAt: plan.CreatedAt,
		Brain: cateringRes.Brain{
			ID:      audio.ID,
			Title:   audio.Title,
			Briefly: audio.Briefly,
			Cover:   audio.Cover,
		},
		Sport: cateringRes.Sport{
			ID:      video.ID,
			Title:   video.Title,
			Briefly: video.Briefly,
			Cover:   video.Cover,
		},
		Breakfast: cateringRes.Breakfast{
			ID:      breakfast.ID,
			Title:   breakfast.Title,
			Briefly: breakfast.Briefly,
			Cover:   breakfast.Cover,
		},
		Lunch: cateringRes.Lunch{
			ID:      lunch.ID,
			Title:   lunch.Title,
			Briefly: lunch.Briefly,
			Cover:   lunch.Cover,
		},
		Dinner: cateringRes.Dinner{
			ID:      dinner.ID,
			Title:   dinner.Title,
			Briefly: dinner.Briefly,
			Cover:   dinner.Cover,
		},
	}
	return
}
